/* Copyright(C): Leaf Johnson 2009,2010

    This file is part of leaf-lib.

    leaf-lib is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    leaf-lib is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with leaf-lib.  If not, see <http://www.gnu.org/licenses/>.


 * 
 * 
 */


#include <devices_ext/uartutils.h>
#include <devices/uart.h>
#include <string.h>

/* 在timeout限定的时间内
 * 从指定串口port读入一个起始字节为header，长度(包含首部)为msglen的消息，保存在buf里
 * 优点是在接收定长消息时，有一定的优化。
 * 有一消息  XXXHDDDD
 * 找啊找之后    hpos = 3
 * 有hpos个数据不要了，需要重新读进来
 * 先要把它们抹掉也就成了 HDDDD???(rd)
 *                         pos = rd - hpos
 *   */
int uart_read_header_msg( uint8_t port, void *buf, size_t msglen, uint8_t header, unsigned int timeout )
{
	int rd;
	uint8_t *dest = (uint8_t *)buf;
	uart_set_timeout( port, timeout );
	rd = uart_read( port, dest, msglen );
	if( rd <= 0 )
		return rd;
	size_t junkctr;
	for( junkctr = 0; junkctr < rd; ++junkctr )
	{
		if( dest[junkctr] == header ){
			if( junkctr > 0 ){
				memmove( &dest[0], &dest[junkctr], rd - junkctr );
				uart_set_timeout( port, timeout );
				if( uart_read( port, &dest[ rd - junkctr ], junkctr ) < junkctr ){
					rd -= junkctr;
				}
			}
			break;
		}
	}
	return rd;
}

